package server;

import java.rmi.Naming;
import java.rmi.RMISecurityManager;
import java.rmi.RemoteException;
import java.rmi.registry.LocateRegistry;
import java.rmi.registry.Registry;
import java.rmi.server.UnicastRemoteObject;
import java.util.HashMap;
import java.util.Set;

import subject.ISubject;
import subject.Subject;

@SuppressWarnings("serial")
public class Server extends UnicastRemoteObject implements IServer {

	private HashMap<String, ISubject> mapsubject;
	
	public Server() throws RemoteException {
		super();
		 mapsubject = new HashMap<String, ISubject>();
	}

	public ISubject getSubject(String name) throws RemoteException {
		ISubject subject;
		System.out.println(mapsubject);
		if(mapsubject.containsKey(name)){
			subject = mapsubject.get(name);
		}else{
			subject=new Subject(name);
			mapsubject.put(name, subject);
		}
		return subject;
	}

	public void disconnectSubject(String nameClient) throws Exception {
		ISubject subject = mapsubject.get(nameClient);
		if(subject!=null){
			subject.removeClient(nameClient);
		}
	}


	public void connectSubject(String name,String indentifiant) throws Exception {
		ISubject sub=getSubject(indentifiant);
		if(sub!=null){
			sub.addClient(indentifiant);
		}else{
			sub = new Subject(name);
			sub.addClient(indentifiant);
			mapsubject.put(name, sub);
		}
	}
	public Set<String> getSubjects() {
		// TODO Auto-generated method stub
		return null;
	}
//TODO Gestion des pseudo 
	public static void main(String[] argv) {
		System.out.println("RMI server started");
        System.setProperty("java.security.policy","java.security.AllPermission");
 
        // Create and install a security manager
        if (System.getSecurityManager() == null) {
            System.setSecurityManager(new RMISecurityManager());
            System.out.println("Security manager installed.");
        } else {
            System.out.println("Security manager already exists.");
        }
 
        try { //special exception handler for registry creation
            LocateRegistry.createRegistry(1099); 
            System.out.println("java RMI registry created.");
        } catch (RemoteException e) {
            //do nothing, error means registry already exists
            System.out.println("java RMI registry already exists.");
        }
 
        try {
            //Instantiate RmiServer
            IServer server = new Server();
            // Bind this object instance to the name "RmiServer"
            Naming.rebind("//localhost/RmiServer", server);
            Subject s =new Subject("Cinéma");
            System.out.println("PeerServer bound in registry");
        } catch (Exception e) {
            System.err.println("RMI server exception : " + e);
            e.printStackTrace();
        }
	}

	

}
